/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *    2012 year
 *    Author: Michael Khromov aka MikeDM (Mike D'Morto)
 *    E-Mail: mikedmorto@gmail.com
 */

#include "worker.h"

Worker::Worker(const QString &cfg, const QString sessionID, QObject *parent) :
    QThread(parent)
{
    this->sessionID = sessionID;
    QStringList cfglist = cfg.split(",");
    // поиск dbhost
    this->dbhost="";
    for(int i = 0 ; i < cfglist.size(); i++){
        QStringList a = cfglist.at(i).split("=");
        if(a.at(0) == "host" and a.size() >= 2 ){
            this->dbhost = a.at(1);
        }
    }
    // поиск dbsocket;
    this->dbsocket="";
    for(int i = 0 ; i < cfglist.size(); i++){
        QStringList a = cfglist.at(i).split("=");
        if(a.at(0) == "socket" and a.size() >= 2 ){
            this->dbsocket = a.at(1);
        }
    }
    // поиск порта
    this->dbport=DEF_DBPORT;
    for(int i = 0 ; i < cfglist.size(); i++){
        QStringList a = cfglist.at(i).split("=");
        if(a.at(0) == "port" and a.size() >= 2 ){
            this->dbport = a.at(1).toInt();
        }
    }
    // поиск login
    this->dbusername="";
    for(int i = 0 ; i < cfglist.size(); i++){
        QStringList a = cfglist.at(i).split("=");
        if(a.at(0) == "login" and a.size() >= 2 ){
            this->dbusername = a.at(1);
        }
    }
    // поиск password
    this->dbpassword="";
    for(int i = 0 ; i < cfglist.size(); i++){
        QStringList a = cfglist.at(i).split("=");
        if(a.at(0) == "password" and a.size() >= 2 ){
            this->dbpassword = a.at(1);
        }
    }
    // поиск database name
    this->dbname="";
    for(int i = 0 ; i < cfglist.size(); i++){
        QStringList a = cfglist.at(i).split("=");
        if(a.at(0) == "base" and a.size() >= 2 ){
            this->dbname = a.at(1);
        }
    }
    // самозапускаемся.
    this->start();
}


void Worker::slotTransactionStart(){

}

void Worker::slotTransactionCommit(){

}

void Worker::slotTransactionRollback(){

}

void Worker::slotQuery(const QString &metafunction, QStringList params){

}

void Worker::stopT(){
    // останавливаем поток.
    this->isStop=true;
}

QString Worker::sqlsafe(const QString & str){
    QString aa = str;
    aa.replace("\\","\\\\");
    aa.replace("\"","\\\"");
    aa.replace("'","\\'");
    return aa;
}

// рабочий цикл потока
void Worker::run(){
    // запускаем соединение с бд
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL",sessionID);
    // конфигурируем.
    if(!this->dbsocket.isEmpty()){
        db.setConnectOptions(QString("UNIX_SOCKET=%1").arg(this->dbsocket));
    }else{
        db.setHostName(this->dbhost);
        db.setPort(this->dbport);
    }
    db.setDatabaseName(this->dbname);
    db.setUserName(this->dbusername);
    db.setPassword(this->dbpassword);
    if(!db.open()){
        // ошибка соединения с бд
        this->sigPutLog(WRK_NAME,1,QString("failure connect to database en thread %1").arg(this->sessionID));
        emit this->sigError(this->sessionID,QString("connection error - %1").arg(db.lastError().text()));
    }else{
        this->sigPutLog(WRK_NAME,2,QString("success connect to database en thread %1").arg(this->sessionID));
        this->isStop = false;
        for(;;){
            QTime dieTime= QTime::currentTime().addMSecs(1);
            while( QTime::currentTime() < dieTime )
            QCoreApplication::processEvents(QEventLoop::AllEvents, 100);


            // есть ли флаг остановки
            if(this->isStop){
                this->sigPutLog(WRK_NAME,2,QString("terminate thread %1").arg(this->sessionID));
                db.close();
                this->terminate();
            }else{
                // тело



            }
        }
    }
}
